package org.jeecg.modules.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.Date.DateUtil;
import org.jeecg.common.util.mall.HttpUtils;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.constant.TaskNamesConstant;
import org.jeecg.modules.appuser.entity.TbUserVip;
import org.jeecg.modules.appuser.entity.TbUserWallet;
import org.jeecg.modules.appuser.entity.TbUserWalletDetail;
import org.jeecg.modules.appuser.service.ITbUserIntegralService;
import org.jeecg.modules.appuser.service.ITbUserVipService;
import org.jeecg.modules.appuser.service.ITbUserWalletDetailService;
import org.jeecg.modules.appuser.service.ITbUserWalletService;
import org.jeecg.modules.mall.entity.TbMnOrder;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.mapper.TbMnOrderMapper;
import org.jeecg.modules.mall.service.ITbMnAdzoneService;
import org.jeecg.modules.mall.service.ITbMnOrderService;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 淘宝订单
 * @Author: jeecg-boot
 * @Date: 2020-05-12
 * @Version: V1.0
 */
@Service
@Slf4j
public class TbMnOrderServiceImpl extends ServiceImpl<TbMnOrderMapper, TbMnOrder> implements ITbMnOrderService {

    @Autowired
    @Lazy(true)
    private ITbMnOrderService tbMnOrderService;

    @Autowired
    private ITbMnAdzoneService tbMnAdzoneService;

    @Autowired
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ITbUserVipService tbUserVipService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;

    @Autowired
    private ITbUserIntegralService tbUserIntegralService;

    @Autowired
    private ISysDictService sysDictService;

    @SneakyThrows
    @Override
    public void queryOrderByTask(String parameter) {
        String json = getOrderJson(parameter);
        if ("[]".equals(json)) {
            return;
        }
        String error = JSON.parseObject(json).getString("error");
        if (null != error) {
            log.info(error);
        } else {
            String result_str = JSON.parseObject(json).getJSONObject("data").getString("results");
            if (!StringUtils.isEmpty(result_str) && !result_str.equals("[]")) {
                String resultStr = JSON.parseObject(result_str).getString("publisher_order_dto");
                if (null != resultStr && resultStr.length() > 2) {
                    List<TbMnOrder> tbMnOrderList = JSON.parseArray(resultStr, TbMnOrder.class);
                    for (TbMnOrder tbMnOrder : tbMnOrderList) {
                        //判断表内是否存在，如果存在则更新
                        if (saveOrder(tbMnOrder)) continue;
                    }
                }
            }
        }
    }

    public void updateWalletData(TbMnOrder tbMnOrder, QueryWrapper queryWrapper) {
        if (3 == tbMnOrder.getTkStatus()) {
            //返佣
            String adzoneId = tbMnOrder.getAdzoneId();
            //查询用户
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("trade_id", tbMnOrder.getTradeId());
            TbMnOrder tbMnOrder1 = tbMnOrderService.getOne(queryWrapper1);
            if (tbMnOrder1.getRebateStatus() == 0) {
                TbMnUser tbMnUser = tbMnAdzoneService.getOneByAdzone(adzoneId);
                tbMnOrder.setRebateStatus(1);
                //返佣三级
                int rebate_layer_num = 3;
                RebateUser(tbMnOrder1, tbMnUser, rebate_layer_num);
                //  增加个人积分一次
                if (null != tbMnUser) {
                    Map<String, Object> resultData1 = tbUserIntegralService.doActionTask(tbMnUser.getId(), TaskNamesConstant.Task_SELF_PURCHASE_GOODS);
                    log.info("增加个人积分一次--->" + resultData1.toString());
                }
            }

        }
        tbMnOrderService.update(tbMnOrder, queryWrapper);
    }

    //升级用户等级
    private boolean upgradeUserGrade(TbMnUser tbMnUser) {

        BigDecimal profit = new BigDecimal(0);
        if (null != tbMnUser) {
            QueryWrapper userWalletQueryWrapper = new QueryWrapper();
            userWalletQueryWrapper.eq("user_id", tbMnUser.getId());
            userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
            List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
            if (null != tbUserWalletDetailList && tbUserWalletDetailList.size() > 0) {
                for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                    profit = profit.add(tbUserWalletDetail.getPayNumber());
                }

            }
            log.info(tbMnUser.getPhone() + "用户升级---------------------------------->" + profit);
            //得到上一等级
            TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
            int next_srot = tbUserVip.getSort() + 1;
            QueryWrapper vipQueryWrapper = new QueryWrapper();
            vipQueryWrapper.eq("sort", next_srot);
            TbUserVip next_tbUserVip = tbUserVipService.getOne(vipQueryWrapper);
            if (null == next_tbUserVip) {
                log.info("你已经是最高等级了");
            } else {

                BigDecimal next_tbUserVipBalanceMin = next_tbUserVip.getInviteProfit();
                if (profit.compareTo(next_tbUserVipBalanceMin) >= 0) {
                    //升级
                    tbMnUser.setVipId(next_tbUserVip.getId());
                    tbMnUser.setVipName(next_tbUserVip.getVipName());
                    String bigDecimal = next_tbUserVip.getFirstRebate().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
                    tbMnUser.setOwnRate(bigDecimal);
                    tbMnUserService.updateById(tbMnUser);
                    log.info("{}升级成功,手机号码{}", tbMnUser.getAccount(), tbMnUser.getPhone());
                    return true;
                }
            }
        }

        return false;
    }

    private void RebateUser(TbMnOrder tbMnOrder1, TbMnUser tbMnUser, Integer rebate_layer_num) {

        if (rebate_layer_num > 0) {
            if (null != tbMnUser) {
                //得到用户等级
                TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
                BigDecimal firstRebate = null;
                if (rebate_layer_num == 3) {
                    firstRebate = tbUserVip.getFirstRebate();
                }
                if (rebate_layer_num == 2) {
                    firstRebate = tbUserVip.getSecondRebate();
                }
                if (rebate_layer_num == 1) {
                    firstRebate = tbUserVip.getThirdRebate();
                }

                String totalCommissionFee = tbMnOrder1.getTotalCommissionFee();
                BigDecimal totalCommissionFeedec = new BigDecimal(totalCommissionFee);
                BigDecimal upperFirstFee = firstRebate.multiply(totalCommissionFeedec);
                if (upperFirstFee.compareTo(new BigDecimal(0)) > 0) {
                    TbUserWallet tbUserWallet = tbUserWalletService.getOneByUser_id(tbMnUser.getId());
                    synchronized (tbUserWallet) {
                        BigDecimal upperFirstWalletBalance = tbUserWallet.getBalance();
                        BigDecimal new_upperFirstWalletBalance = upperFirstWalletBalance.add(upperFirstFee);
                        tbUserWallet.setBalance(new_upperFirstWalletBalance);

                        if (saveUserWalletDetail(tbUserWallet, upperFirstFee, tbMnUser.getId())) {
                            //资产更新成功
                            if (tbUserWalletService.updateById(tbUserWallet)) {
                                rebate_layer_num = rebate_layer_num - 1;
                                //查询它的被邀请人,进行返佣
                                TbMnUser inviteesUpperFirst = tbMnUserService.getInviteesUpperFirst(tbMnUser);
                                if (null != inviteesUpperFirst) {
                                    RebateUser(tbMnOrder1, inviteesUpperFirst, rebate_layer_num);
                                }
                            }
                        }
                    }
                }
                //用户升级
                upgradeUserGrade(tbMnUser);
            }
        }
    }

    private boolean saveUserWalletDetail(TbUserWallet tbUserWallet, BigDecimal newBalance, String fromUserId) {
        TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
        tbUserWalletDetail.setPayFrom(PayTypeConstant.PAYFORM_REBATE);
        tbUserWalletDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
        tbUserWalletDetail.setPayNumber(newBalance);
        tbUserWalletDetail.setWalletId(tbUserWallet.getId());
        tbUserWalletDetail.setUserId(tbUserWallet.getUserId());
        tbUserWalletDetail.setFromUser(fromUserId);
        tbUserWalletDetail.setBalance(tbUserWallet.getBalance());
        tbUserWalletDetailService.save(tbUserWalletDetail);
        return true;
    }

    private boolean saveOrder(TbMnOrder tbMnOrder) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("trade_id", tbMnOrder.getTradeId());
        List<TbMnOrder> tbMnOrderList = this.baseMapper.selectList(queryWrapper);
        TbMnOrder mnOrder = null;
        if (null != tbMnOrderList && tbMnOrderList.size() > 1) {
            mnOrder = tbMnOrderList.get(0);
        } else {
            mnOrder = this.baseMapper.selectOne(queryWrapper);
        }
        if (null != mnOrder) {
            updateWalletData(mnOrder, queryWrapper);
            return true;
        } else {
            tbMnOrder.setRebateStatus(0);
            this.baseMapper.insert(tbMnOrder);
        }

        return false;
    }

    private String getOrderJson(String parameter) throws IOException {

        //得到默认配置的时间
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("order_start_time");
        String daynum = "0";
        if (null != dictModelList && dictModelList.size() > 0) {
            daynum = dictModelList.get(0).getValue();
        }
        if (!StringUtils.isEmpty(parameter)) {
            daynum = parameter;
        }
        String dateTime = DateUtil.getBeforeDateByMinute(-1);
        String tenBefore = "";
        String end_time = DateUtil.getEndDateByMinute(0);
        //7天后在采集一次订单详情
        if (!org.apache.commons.lang3.StringUtils.isEmpty(daynum) && !daynum.equals("0")) {
            dateTime = DateUtil.getTenBeforeDate(Integer.valueOf(daynum));
            end_time = DateUtil.getEndBeforeDate(Integer.valueOf(daynum));
        }

        try {
            tenBefore = URLEncoder.encode(dateTime, "utf8");
            end_time = URLEncoder.encode(end_time, "utf8");
        } catch (UnsupportedEncodingException e) {
            log.error("urlencoder编码失败，msg:{}", e.getMessage());
            log.error(e.getMessage(), e);
        }
        String url = Contents.HM_URL + "?appkey=" + Contents.HM_APPKEY + "&appsecret=" + Contents.HM_APPSECRET
                + "&sid=12081&start_time=" + tenBefore + "&end_time=" + end_time + "&query_type=1&tk_status=&order_scene=1&member_type=&page_no=1&page_size=100&position_index=";

        String json = HttpUtils.httpClientGet(url, "");

        log.info("自动查询订单,resp:{}", json);
        return json;
    }

    @Override
    public void queryOrderAndUpdate() throws IOException {
        //查询所有未结算的订单
        List<Short> values = new ArrayList<>();
        values.add((short) 12);
        values.add((short) 14);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("tk_status", values);
        List<TbMnOrder> tbMnOrderList = this.baseMapper.selectList(queryWrapper);
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("order_start_time");
        for (TbMnOrder tbMnOrder : tbMnOrderList) {
            String daynum = "0";
            if (null != dictModelList && dictModelList.size() > 0) {
                daynum = dictModelList.get(0).getValue();
            }
            String dateTime = DateUtil.getTenBeforeDate(Integer.valueOf(daynum));
            String tenBefore = "";
            String end_time = DateUtil.getEndBeforeDate(Integer.valueOf(daynum));
            try {
                tenBefore = URLEncoder.encode(dateTime, "utf8");
                end_time = URLEncoder.encode(end_time, "utf8");
            } catch (UnsupportedEncodingException e) {
                log.error("urlencoder编码失败，msg:{}", e.getMessage());
                log.error(e.getMessage(), e);
            }
            String url = Contents.HM_URL + "?appkey=" + Contents.HM_APPKEY + "&appsecret=" + Contents.HM_APPSECRET
                    + "&sid=12081&start_time=" + tenBefore + "&end_time=" + end_time + "&query_type=1&tk_status=&order_scene=1&member_type=&page_no=1&page_size=100&position_index=";
            String json = HttpUtils.httpClientGet(url, "");
            JSONObject jsonObject = JSON.parseObject(json);

            json = jsonObject.getString("results");

            log.info("自动查询订单,resp:{}", json);
            if ("[]".equals(json)) {
                return;
            }
            List<TbMnOrder> tbMnOrderList1 = JSON.parseArray(json, TbMnOrder.class);
            for (TbMnOrder tbMnOrder1 : tbMnOrderList1) {
                QueryWrapper queryWrapper_order = new QueryWrapper();
                queryWrapper_order.eq("trade_id", tbMnOrder1.getTradeId());
                updateWalletData(tbMnOrder1, queryWrapper_order);
            }
        }
    }


    /**
     * 淘宝：1）买家超时未付款； 2）买家付款前，买家/卖家取消了订单；3）订单付款后发起售中退款成功；3：订单结算，12：订单付款， 13：订单失效，14：订单成功
     *
     * @param tbMnOrder
     * @param adzoneIds
     * @param pageNo
     * @param pageSize
     * @param tbMnUser
     * @return
     */
    @Override
    public List<TbMnOrder> queryOrderByStatus(TbMnOrder tbMnOrder, List<String> adzoneIds, Integer pageNo, Integer pageSize, TbMnUser tbMnUser) {

        QueryWrapper queryWrapper = new QueryWrapper();
        if (null != tbMnOrder.getTkStatus()) {
            if (!"1".equals(String.valueOf(tbMnOrder.getTkStatus()))) {
                if ("14".equals(String.valueOf(tbMnOrder.getTkStatus()))) {
                    List<Short> values = new ArrayList<Short>();
                    values.add((short) 12);  //  values.add((short) 12);
                    values.add((short) 14);
                    queryWrapper.in("tk_status", values);
                } else {
                    queryWrapper.eq("tk_status", tbMnOrder.getTkStatus());
                }
            }
        }
        queryWrapper.in("adzone_id", adzoneIds);
        queryWrapper.orderByDesc("create_time");

        List<TbMnOrder> tbMnOrderList = this.baseMapper.selectList(queryWrapper);
        TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
        if (null != tbMnOrderList && tbMnOrderList.size() > 0) {
            for (TbMnOrder tbMnOrder1 : tbMnOrderList) {//对预估收入进行结算
                double temp = Double.valueOf(tbMnOrder1.getPubSharePreFee());
                BigDecimal bigDecimal = new BigDecimal(temp).multiply(tbUserVip.getFirstRebate());
                double pubSharePreeFee = bigDecimal.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                tbMnOrder1.setPubSharePreFee(String.valueOf(pubSharePreeFee));
            }
        }

        return tbMnOrderList;
    }
}
